import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'globals.dart' as globals;
import 'websocket.dart';
import 'home_page.dart';
import 'live_page.dart';
import 'history_page.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: '米尔行车记录仪',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MainPage());
  }
}

class MainPage extends StatefulWidget {
  MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  // WebSocketChannel channel = WebSocketChannel.connect(Uri.parse(
  // 'ws://127.0.0.1:28889')); //IOWebSocketChannel.connect('ws://127.0.0.1:28889');
  WebSocket socket = WebSocket(globals.websocketAddr);
  late Stream stream;
  var pages = [HomePage(), null, HistoryPage()];
  var currentIndex = 0;

  @override
  void initState() {
    super.initState();
    socket.connect();
    stream = socket.stream.asBroadcastStream();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("米尔行车记录仪"),
      ),
      body: currentIndex == 1 ? LivePage(stream: stream) : pages[currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        type: BottomNavigationBarType.fixed,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
              backgroundColor: Colors.pink,
              icon: Icon(Icons.home),
              label: "首页"),
          BottomNavigationBarItem(
              backgroundColor: Colors.green,
              icon: Icon(Icons.person),
              label: "实时画面"),
          BottomNavigationBarItem(
              backgroundColor: Colors.orange,
              icon: Icon(Icons.list),
              label: "历史记录"),
        ],
      ),
    );
  }

  @override
  void dispose() {
    socket.disconnect();
    super.dispose();
  }
}
